package guda.mrpc.core.client;


import guda.mrpc.core.api.Request;
import guda.mrpc.core.client.loadblance.LoadBalance;
import guda.mrpc.core.client.loadblance.impl.RoundLoadBalance;
import guda.mrpc.core.transport.ClientHandler;

import java.util.List;


public class RpcInvoker<T> {


    private LoadBalance loadBalance;

    public RpcInvoker(){
        this(new RoundLoadBalance());
    }
    public RpcInvoker(LoadBalance loadBalance){
        this.loadBalance=loadBalance;
    }

    public Object invoke(Request request) throws Exception {
        List<ClientHandler> handlers = ConnectionFactory.instance().getHandlers(request.getKey());
        if(handlers ==null){
            throw new RuntimeException("rpc error, no connection found.");
        }
        ClientHandler selectClientHandler = loadBalance.select(request.getKey());
        if (!selectClientHandler.getChannel().isActive()) {
            throw new RuntimeException("Client Channel is unactive.");
        }
        RpcFuture rpcFuture = selectClientHandler.sendRequest(request);
        if(request.hasResult()){
            Object result = rpcFuture.get();
            return result;
        }else{
            return null;
        }
    }

}